import React, {Component} from 'react';
import {
  CheckOutlined,
  FullscreenExitOutlined,
  FullscreenOutlined,
  HomeOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {Avatar, Breadcrumb, Dropdown, Image, Menu, message, Modal, Tooltip} from 'antd';
import './index.less';
import PropTypes from 'prop-types';
import {beFull, exitFull} from 'be-full';
import {IconFont, theme, themeColors} from '../../utils/config';
import store from 'store';
import lightVars from '../../light.json';
import darkVars from '../../dark.json';
import {Link, withRouter} from 'react-router-dom';
import menuList from "../../utils/menuConfig";
import {verifyTokenExpire} from '../../utils/tools';
import FailImg from '../../assets/fail_img.png';

class TopHeader extends Component {
  menu = (
    <Menu>
      <Menu.Item>
        <span>
          <UserOutlined/>个人中心
        </span>
      </Menu.Item>
      <Menu.Item onClick={() => {
        store.remove('token');
        store.remove('user');
        message.success('退出成功！')
        this.props.history.replace('/admin/login');
      }}>
        <IconFont type="icon-zhuxiao"/>注销
      </Menu.Item>
    </Menu>
  );

  static propTypes = {
    toggle: PropTypes.func.isRequired,
    collapsed: PropTypes.bool.isRequired
  }

  static defaultProps = {
    collapsed: false, // 折叠侧边栏
    isModalVisible: false, // 模态框是否可见
  }

  constructor(props) {
    super(props);
    // 默认 原色 #1890ff ，就是rgb(24, 144, 255)
    let initialValue = lightVars; // 亮色主题的参数
    let vars = {}; // 参数
    let themeName = store.get("theme-name") || 'light'; // 获取主题 ，light/dark,默认light

    try {
      vars = store.get("app-theme"); // 获取当前主题的参数
      if (!vars) {
        vars = initialValue; // 如果没有就设置默认 亮色 主题
      } else {
        let data = typeof vars === 'string' ? JSON.parse(vars) : vars
        vars = Object.assign(
          {},
          data
        );
      }
    } catch (e) {
      vars = initialValue;
    } finally {
      let primaryColor = vars['@primary-color'];
      primaryColor = primaryColor === '@blue-6' ? 'rgb(24, 144, 255)' : primaryColor;
      this.state = {
        themeApplied: false, // 是否导入了主题
        primaryColor,
        vars, initialValue, size: 'default',
        disabled: false,
        themeName,
        full: false,
        backgroundColor: ''
      };
    }
  }

  UNSAFE_componentWillMount() {
    // 设置主题，通过less覆盖变量的方式
    window.less
      .modifyVars(this.state.vars)
      .then(() => {
        // this.setState({themeApplied: true}); // 调用此方式
      })
      .catch(error => {
        message.error(`Failed to update theme`);
      });
  }

  // 将menu的格式转为面包屑专用的格式
  getRoute = (item) => {
    return {
      path: item.key,
      breadcrumbName: item.title
    }
  }

  // 动态生成面包屑的参数列表
  getRouters = () => {
    let arr = []
    const pathname = this.props.location.pathname;
    let menu = JSON.parse(JSON.stringify(menuList));
    if (pathname !== menu[0].key) {
      arr.push(this.getRoute(menu[0]));
      const item = menu.find(item => item.key === pathname); // 匹配menu第一层
      if (item !== undefined && !item.children) {
        arr.push(this.getRoute(item));
      } else {
        const items = menu.filter(item => item.children);
        for (let i of items) {
          const subItem = i.children.find(a => a.key === pathname)
          if (subItem) {
            delete i.children;
            const parentItem = this.getRoute(i);
            parentItem.parent = true;
            arr.push(parentItem);
            arr.push(this.getRoute(subItem));
          }
        }
      }
    }
    return arr.length > 1 ? arr : []
  }

  // 点击折叠按钮
  menuFoldClick = () => {
    const {collapsed} = this.props;
    this.props.toggle(!collapsed);
  }
  // 全屏显示
  fullPage = () => {
    const {full} = this.state;
    if (full) { // true
      exitFull(); // 退出全屏
    } else {
      beFull();
    }
    this.setState({
      full: !full
    })
  }
  // 显示模态框
  showModal = () => {
    const {isModalVisible} = this.state;
    this.setState({
      isModalVisible: !isModalVisible
    })
  }

  componentDidMount() {
    // 刷新时保持颜色修改
    const appTheme = store.get('app-theme');
    if (appTheme && appTheme['@theme'] !== 'dark') {
      const backgroundColor = appTheme['@primary-color'];
      this.setState({
        backgroundColor
      })
    }
  }

  // 修改主题色(原色)
  changePrimaryColor = (varname, color) => {
    this.setState({
      backgroundColor: color
    })
    const vars = {...this.state.vars};
    if (varname) vars[varname] = color;
    window.less.modifyVars(vars)
      .then(() => {
        this.setState({vars, primaryColor: color});
        store.set("app-theme", JSON.stringify(vars));
      })
      .catch(error => {
        message.error(`Failed to update theme`);
      });
  }
  // 修改主题
  changeTheme = (type, value) => {
    let vars = value === 'light' ? lightVars : darkVars;
    vars = {...vars, '@white': '#fff', '@black': '#000'};
    if (value !== 'light') {
      this.backgroundColor = '';
    }
    this.setState({vars, themeName: value});
    this.setState({vars});
    localStorage.setItem("app-theme", JSON.stringify(vars));
    localStorage.setItem("theme-name", value);
    window.less.modifyVars(vars).catch(error => {
      console.log('主题切换失败, error:'+error.message)
    });
  }
  // 渲染图标
  renderCheckOutIcon = (color, bgColor) => {
    if (color === '#1890ff') {
      color = 'rgb(24, 144, 255)';
    }
    return (
      color === bgColor ? <CheckOutlined/> : ''
    )
  }
  // 渲染面包屑
  itemRender = (route, params, routes, paths) => {
    const last = routes.indexOf(route) === routes.length - 1;
    return (last || route.parent) ? (
      <span>{route.breadcrumbName}</span>
    ) : (
      <Link to={route.path}>{route.breadcrumbName}</Link>
    );
  }

  render() {
    const {collapsed} = this.props;
    const {full, isModalVisible, primaryColor, themeName} = this.state;
    // 全局验证是否登录
    const user = store.get('user') || (this.props.location.state && this.props.location.state.user);
    const token = store.get('token');
    if (!user && !token) {
      this.props.history.replace('/admin/login');
    }
    verifyTokenExpire()
    const routes = this.getRouters();
    return (
      user ?
      <div className='wrapper' style={{backgroundColor: this.state.backgroundColor}}>
        <div className='left-content'>
          {
            collapsed ? null :
              <div className='left-nav-header'>
                <h3>资讯后台管理系统</h3>
              </div>
          }
          {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
            className: collapsed ? 'trigger foldout' : 'trigger',
            onClick: this.menuFoldClick,
          })}
          {/*面包屑*/}
          {
            <Breadcrumb itemRender={this.itemRender} routes={routes} style={collapsed ? {marginLeft: 0} : {}}/>
          }
          {/*end*/}
        </div>
        <div className='right-content'>
          {/*全屏*/}
          <Tooltip placement="bottom" title='全屏显示'>
            {React.createElement(full ? FullscreenExitOutlined : FullscreenOutlined, {
              className: 'trigger icon',
              onClick: this.fullPage,
            })}
          </Tooltip>
          {/*首页*/}
          <Tooltip placement="bottom" title='首页'>
            <Link to='/admin'>
              <HomeOutlined className='trigger'/>
            </Link>
          </Tooltip>
          {/*主题*/}
          <Tooltip placement="bottom" title='主题'>
            <IconFont className='trigger' type='icon-zt' onClick={this.showModal}/>
          </Tooltip>
          {/*登录用户*/}
          <Dropdown overlay={this.menu}>
            <div className='user'>
              <Avatar src={<Image preview={false} src={user.avatarUrl} fallback={FailImg} />}/>
              <span className='username'>
                {user.nickName || '未知用户'}
            </span>
            </div>
          </Dropdown>
        </div>
        <Modal title="改变主题"
               width={400}
               footer={null}
               visible={isModalVisible}
               onCancel={this.showModal}>
          <span>主题整体风格</span>
          <div className='theme-overall-style'>
            {
              theme.map(item =>
                (
                  <Tooltip placement="topLeft" title={item.title} key={item.id}>
                    <div className={'theme-item-box ' + item.className}
                         onClick={() => this.changeTheme(item.type, item.type)}>
                      {
                        themeName === item.type ? <CheckOutlined className='theme-item-box-checkout'/> : ''
                      }
                    </div>
                  </Tooltip>
                )
              )
            }
          </div>
          <span>主题色</span>
          <div className='theme-color'>
            <div className='theme-color-content'>
              {
                themeColors.map(item => {
                  return (
                    <Tooltip placement="topLeft" title={item.bgTxt} key={item.id}>
                      <div className='theme-color-block'
                           key={item.id}
                           style={{backgroundColor: item.bgColor}}
                           onClick={(e) => {
                             this.changePrimaryColor('@primary-color', item.bgColor)
                           }}
                      >
                        {
                          this.renderCheckOutIcon(primaryColor, item.bgColor)
                        }
                      </div>
                    </Tooltip>
                  )
                })
              }
            </div>
          </div>
        </Modal>
      </div>
        : null
    )
  }
}
// 需要使用面包屑，所以将其转为router组件
export default withRouter(TopHeader);
